package com.example.registration;

import android.Manifest;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import com.example.registration.utils.ImageHelper;
import com.example.registration.utils.PermissionHelper;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.Base64;
import java.util.List;

public class MainActivity extends Activity implements PermissionHelper.PermissionCallback {

    private WebView webView;

    private int PICK_IMAGE_REQUEST = 1002;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 设置xml样式
        setContentView(R.layout.activity_main);

        // 获取webView元素
        webView = findViewById(R.id.webview);

        // 启用JavaScript
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);

        // 设置WebViewClient来拦截URL加载
        webView.setWebViewClient(new WebViewClient());

        // 设置js接口
        webView.addJavascriptInterface(new WebAppInterface(this), "Android");

        // 加载H5页面
        webView.loadUrl("http://192.168.2.111:3000/#/home");

        boolean check = PermissionHelper.hasPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);
        if (!check) {
            String[] requestPerm = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE};
            PermissionHelper.requestPermissions(this, requestPerm, PICK_IMAGE_REQUEST, this);
        }
    }

    @Override
    public void onPermissionGranted() {

    }

    @Override
    public void onPermissionDenied(List<String> deniedPermissions) {

    }


    /**
     * desc: H5控制安卓屏幕转向的问题
     * use: H5使用方法<button onclick="Android.setScreenOrientationLandscape()">Set Landscape</button>
     */
    public class WebAppInterface {
        Context mContext;

        WebAppInterface(Context c) {
            mContext = c;
        }


        /**
         * 请求读取相册图片功能
         */
        @JavascriptInterface
        public void getPicture() {
            pickImageFromGallery();
        }


        /**
         * 保存处理好的图片
         */
        @JavascriptInterface
        public void savePicture(String imageBase64) {
            Bitmap bit = ImageHelper.base642Bitmap(imageBase64);
            saveImageToGallery(bit);
        }


        /**
         * 读取手机内文件
         */
        private void pickImageFromGallery() {
            Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(intent, PICK_IMAGE_REQUEST);
        }

    }

    public void saveImageToGallery(Bitmap bitmap) {
        String filename = "IMG_" + System.currentTimeMillis() + ".jpg";
        String savedImageURL = MediaStore.Images.Media.insertImage(
                getContentResolver(),
                bitmap,
                filename,
                "Image of " + filename
        );

        if (savedImageURL != null) {
            Toast.makeText(this, "图片保存到相册成功！", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "图片保存到相册失败！", Toast.LENGTH_SHORT).show();
        }
    }


    /**
     * 其他应用回调处理
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //系统相册读取
        if (resultCode == RESULT_OK && requestCode == PICK_IMAGE_REQUEST) {
            Uri imageUri = data.getData();
            try {
                // 获取内容解析器
                ContentResolver contentResolver = getContentResolver();
                // 读取图片的二进制数据
                InputStream inputStream = contentResolver.openInputStream(imageUri);
                Bitmap bitmap = BitmapFactory.decodeStream(inputStream);

                // 如果需要将Bitmap转换为二进制数组
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
                byte[] imageBytes = baos.toByteArray();
                String base64Image = Base64.getEncoder().encodeToString(imageBytes);
                String js = "javascript:AndroidCallback(" + "'" + base64Image + "'" + ")";
                webView.evaluateJavascript(js, new ValueCallback<String>() {
                    @Override
                    public void onReceiveValue(String s) {
                        System.out.println(s);
                    }
                });

                inputStream.close();

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
